<template>
  <div>
    <search-main
      :inputValue="formData.keyword"
      :gjFlag="gjFlag"
      @handleSearch="handleSearch"
    />
    <div class="container_width basicsearch_wrap">
      <div class="fl search_left">
        <el-card class="box-card mb-10">
          <div class="title">全部标准分类</div>
          <el-empty
            v-if="standardList.length == 0"
            description="暂无标准分类"
          ></el-empty>
          <div
            class="standard_class"
            v-for="(item, index) in standardList"
            :key="index"
            @mouseover="hoverClass(index)"
            @mouseout="outClass"
          >
            <span class="">{{ item.className }} </span>
            <span class="item_center"
              >( <span class="num_color">{{ item.total }}</span> )</span
            >
            <i class="fr el-icon-arrow-right"></i>
          </div>
          <!-- 二级分类 -->
          <div
            v-if="standardList.length > 0"
            :class="['second_standard', isActive ? 'activeStyle' : '']"
            @mouseover="hoverSecond"
            @mouseout="outClass"
          >
            <a
              class="second_item"
              v-for="(itm, idx) in standardList[activeHover].child"
              :key="idx"
              @click="
                handleClass(standardList[activeHover].classCode, itm.classCode)
              "
              >{{ itm.className }}(
              <span class="num_color">{{ itm.total }}</span> )</a
            >
          </div>
        </el-card>
        <el-card class="box-card box-card2">
          <div class="title">标准动态</div>
          <div
            class="standard_item"
            v-for="(item, index) in standardTrends"
            :key="index"
            @click="goPath('/basicsearch/detail', item.standardNo, item)"
          >
            <span class="item_center">{{ item.title }}</span>
            <span class="item_right">{{ item.standardStatus }}</span>
          </div>
          <img
            src="../../assets/index_more.jpg"
            alt=""
            class="more_img"
            @click="goPath('/trends')"
          />
        </el-card>
      </div>
      <div class="fr search_right">
        <el-card class="box-card mb-10">
          <el-form
            ref="formData"
            :model="formData"
            label-width="100px"
            class="form_search"
          >
            <el-form-item label="筛选：">
              <el-checkbox v-model="checkPdfAll" @change="handleCheckAllPdf"
                >全部</el-checkbox
              >
              <el-checkbox-group
                v-model="formData.havePdf"
                @change="handleChangePdf"
              >
                <el-checkbox
                  v-for="item in checkPdf"
                  :label="item.value"
                  :key="item.value"
                  >{{ item.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="有效性：">
              <el-checkbox
                v-model="checkStatusAll"
                @change="handleCheckAllStatus"
                >全部</el-checkbox
              >
              <el-checkbox-group
                v-model="formData.status"
                @change="handleChangeStatus"
              >
                <el-checkbox
                  v-for="item in checkExp"
                  :label="item.value"
                  :key="item.value"
                  >{{ item.value }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="年代：">
              <el-checkbox
                v-model="checkModiDateAll"
                @change="handleCheckAllModiDate"
                >全部</el-checkbox
              >
              <el-checkbox-group
                v-model="formData.modiDate"
                @change="handleChangeModiDate"
              >
                <el-checkbox
                  v-for="item in checkPeriod"
                  :label="item.value"
                  :key="item.value"
                  >{{ item.value }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <el-button class="screen_btn" type="primary" @click="getList(1)"
            >筛选</el-button
          >
        </el-card>
        <el-card class="box-card mb-10">
          <el-table
            :data="tableData"
            style="width: 100%"
            tooltip-effect="dark"
            :header-cell-style="{ 'background-color': '#f5f7fa' }"
          >
            <el-table-column prop="standardNo" label="标准号" width="190">
              <template slot-scope="scope">
                <div
                  class="pointer"
                  @click="goPath('/basicsearch/detail', scope.row.standardNo)"
                  v-html="scope.row.standardNo"
                ></div>
              </template>
            </el-table-column>
            <el-table-column
              prop="title"
              label="标准名称"
              show-overflow-tooltip
              width="380"
            >
              <template slot-scope="scope">
                <div
                  class="pointer text-hidden"
                  @click="goPath('/basicsearch/detail', scope.row.standardNo)"
                  v-html="scope.row.title"
                ></div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.status == '现行'" class="num_green">{{
                  scope.row.status
                }}</span>
                <span v-else-if="scope.row.status == '即将实施'" class="num_yel">{{
                  scope.row.status
                }}</span>
                <span v-else-if="scope.row.status == '被代替'" class="num_gray">{{
                  scope.row.status
                }}</span>
                <span v-else class="num_color">{{
                  scope.row.status
                }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="" label="">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="downloadFile(scope.row)">
                  下载
                </el-button>
                <el-button size="mini" type="primary" @click="goReadOnline(scope.row)">在线阅读</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination_wrap">
            <div>
              共<span class="num_color"> {{ total }} </span>条记录
            </div>
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNo"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="100"
              layout=" sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
  import { Loading } from "element-ui";
import SearchMain from "@/components/SearchMain.vue";
import { basicSearch,readOnlineNotify,fileUrl, downLoadNotify} from "@/api/search.js";
import { standardDynamics } from "@/api/home.js";
export default {
  name: "Basicsearch",
  components: {
    SearchMain,
  },
  data() {
    return {
      gjFlag: false,
      activeHover: 0,
      isActive: false,
      checkPdf: [
        {
          value: 1,
          label: "有电子文本",
        },
        {
          value: 0,
          label: "无电子文本",
        },
      ],
      checkExp: [
        {
          value: "现行",
        },
        {
          value: "即将实施",
        },
        {
          value: "被代替",
        },
        {
          value: "废止",
        },
        {
          value: "废止转行标",
        },
      ],
      checkPeriod: [
        {
          value: "2024",
        },
        {
          value: "2023",
        },
        {
          value: "2022",
        },
        {
          value: "2021",
        },
        {
          value: "2020",
        },
        {
          value: "2019及以前",
        },
      ],
      standardList: [],
      formData: {
        status: [], //有效性
        modiDate: [], //年份
        keyword: "", //检索词
        havePdf: [], //是否有电子文本
      },
      tableData: [],
      standardTrends: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      checkStandardAll: false,
      checkPdfAll: false,
      checkStatusAll: false,
      checkModiDateAll: false,
      standardClass: "", //	父分类编码
      classCode: "", //		所属子分类编码
      classFlag: false, // 重新给标准分类赋值
      downloadLoading: null,
      readOnlineStatus:true,
      downloadStatus:true,
    };
  },
  created() {
    this.formData.keyword = this.$route.query.search;
    this.getTrends();
    this.getList();
    this.classFlag = true;
  },
  methods: {
    getList(pageNo) {
      this.pageNo = pageNo ? pageNo : this.pageNo;
      let params = {
        status: this.checkStatusAll ? "" : this.formData.status.join(","),
        modiDate: this.checkModiDateAll ? "" : this.formData.modiDate.join(","),
        keyword: this.formData.keyword,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        standardClass: this.standardClass,
        classCode: this.classCode,
        havePdf: this.checkPdfAll ? "" : this.formData.havePdf.join(","),
      };
      basicSearch(params).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.data;
          this.total = res.data.page.total;
          this.readOnlineStatus = res.data.readOnlineStatus;
          this.downloadStatus = res.data.downloadStatus;
          if (this.classFlag) {
            this.standardList = res.data.standardClass;
          }
        }
        this.classFlag = false;
      });
    },
    getTrends() {
      standardDynamics({pageNo:0,pageSize:7}).then((res) => {
        if (res.code == 200) {
          this.standardTrends = res.data.content;
        }
      });
    },
    handleClass(standardClass, classCode) {
      this.standardClass = standardClass;
      this.classCode = classCode;
      this.getList(1);
      this.outClass();
    },
    handleSearch(value) {
      if (value == "") {
        this.$message({
          message: "请输入内容进行检索！",
          type: "warning",
        });
        return;
      } 
      this.formData.keyword = value;
      // 重新输入关键字 清空筛选项
      this.checkStatusAll = false;
      this.checkModiDateAll = false;
      this.checkPdfAll = false;
      this.formData.status = [];
      this.formData.modiDate = [];
      this.formData.havePdf = [];
      this.pageNo = 1;
      this.pageSize = 10;
      this.standardClass = "";
      this.classCode = "";
      this.classFlag = true;
      this.getList();
    },
    // 电子文本
    handleCheckAllPdf() {
      this.formData.havePdf = this.checkPdfAll
        ? this.checkPdf.map((item) => {
            return item.value;
          })
        : [];
    },
    handleChangePdf(value) {
      let checkedCount = value.length;
      this.checkPdfAll = checkedCount === this.checkPdf.length;
    },
    // 全选有效性
    handleCheckAllStatus() {
      this.formData.status = this.checkStatusAll
        ? this.checkExp.map((item) => {
            return item.value;
          })
        : [];
    },
    handleChangeStatus(value) {
      let checkedCount = value.length;
      this.checkStatusAll = checkedCount === this.checkExp.length;
    },
    // 全选年代
    handleCheckAllModiDate() {
      this.formData.modiDate = this.checkModiDateAll
        ? this.checkPeriod.map((item) => {
            return item.value;
          })
        : [];
    },
    handleChangeModiDate(value) {
      let checkedCount = value.length;
      this.checkModiDateAll = checkedCount === this.checkPeriod.length;
    },
    hoverClass(index) {
      this.activeHover = index;
      this.isActive = true;
    },
    outClass() {
      this.isActive = false;
    },
    hoverSecond() {
      this.isActive = true;
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    goPath(path, no, row) {
      if (row) {
        this.$router.push({
          path,
          query: {
            row: JSON.stringify(row),
          },
        });
        return;
      } else {
        if (no) {
          let str = this.replaceHTML(no)
          this.$router.push({
            path,
            query: {
              no:str,
            },
          });
        } else {
          this.$router.push({
            path,
          });
        }
      }
    },
    downloadFile(row) {
      if(!this.downloadStatus){
        this.$message({
          message: "您的套餐余额不足！",
          type: 'warning'
        })
        return
      }
      this.fileUrl(row,1)
    },
    goReadOnline(row) {
      if(!this.readOnlineStatus){
        this.$message({
          message: "您的套餐余额不足！",
          type: 'warning'
        })
        return
      }
      this.fileUrl(row,0) 
    },
    readOnlineNotify(standardNo,title) {
      readOnlineNotify({
        standardNo,
        title,
      }).then((res) => {
        if(res.code==200){
          this.readOnlineStatus = res.data
        }
      });
    },
    downLoadNotify(standardNo,title) {
      downLoadNotify({
        standardNo,title
      }).then((res) => {
        if(res.code==200){
          this.downloadStatus = res.data
        }
      });
    },
    // 获取pdf链接
    fileUrl(row,type) {
      let standardNo = this.replaceHTML(row.standardNo)
      let title = this.replaceHTML(row.title)
      fileUrl({
        standardNo:standardNo
      }).then(async (res) => {
        if(res.code==200 && res.data!=null){
          if(type==0){//type==0 在线阅读  type==1 下载
            this.readOnlineNotify(standardNo,title);
          let route = this.$router.resolve({ path: '/pdf'});
          sessionStorage.setItem('urlLink',res.data)
          window.open(route.href,'_blank');
          }else if(type==1){
            this.downloadLoading = Loading.service({
        lock: true,
        text: "正在下载中，请稍后...",
        background: "rgba(0, 0, 0, 0.3)",
      });
      try {
        let url = res.data;
        let response = await fetch(url);
        // 内容转变成blob地址
        let blob = await response.blob();
        // 创建隐藏的可下载链接
        let objectUrl = window.URL.createObjectURL(blob);
        let a = document.createElement("a");
        a.style.display = "none";
        //地址
        a.href = objectUrl;
        //修改文件名
        a.download = standardNo + ".pdf";
        // 触发点击
        document.body.appendChild(a);
        a.click();
        //移除
        URL.revokeObjectURL(a.href);
      } catch (err) {
        this.downloadLoading.close();
      } finally {
        this.downloadLoading.close();
        this.downLoadNotify(standardNo,title);
      }
          }

        }else{
          this.$message({
          message: "暂无文本信息！",
          type: 'warning'
        })
        return
        }
      });
    },
    replaceHTML(html){
      var str = html.replaceAll('<font color=red>', "")
      var text = str.replaceAll('</font>', "")
      return text
    }
  },
};
</script>

<style lang="scss">
.basicsearch_wrap {
  height: 850px;
  padding-top: 20px;
  .search_left {
    width: 280px;
    height: 500px;
    .box-card {
      width: 100%;
      position: relative;
      overflow: visible;
      min-height: 300px;
      .el-card__body {
        padding: 0;
        border-radius: 4px 4px 0 0;
        border-top: 10px solid #2f74d3;
        .title {
          height: 50px;
          line-height: 50px;
          color: #2f74d3;
          text-align: center;
          font-size: 18px;
          border-bottom: 1px solid #d9e0e8;
        }
      }
      .standard_class {
        padding: 0 20px;
        line-height: 50px;
        font-size: 16px;
        cursor: pointer;
        &:hover {
          background-color: #9bdcfc;
          font-weight: bold;
          opacity: 0.7;
          .el-icon-arrow-right {
            opacity: 0;
          }
        }
        .item_center {
          padding-left: 10px;
        }
        .el-icon-arrow-right {
          margin-top: 17px;
        }
      }
      .second_standard {
        display: none;
        position: absolute;
        left: 278px;
        top: 60px;
        width: 600px;
        min-height: 300px;
        background-color: #fff;
        z-index: 100;
        padding: 20px;
        border: 2px solid #9bdcfc;
        border-left: 0;
        line-height: 30px;
        .second_item {
          display: inline-block;
          padding: 0 20px;
          font-size: 14px;
          border-left: 1px solid #cccccc;
          min-width: 100px;
          line-height: 16px;
          color: #2f74d3;
        }
      }
      .activeStyle {
        display: block;
      }
    }
    .box-card2 {
      position: relative;
      padding-bottom: 34px;
      .standard_item {
        line-height: 33px;
        border-bottom: 1px dashed #ccc;
        display: flex;
        font-size: 14px;
        padding: 5px 12px;
        span {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        .item_center {
          width: 195px;
          padding-right: 10px;
        }

        &:last-of-type {
          border-bottom: none;
        }
        &:hover {
          cursor: pointer;
          color: #2f74d3;
        }
      }
    }
  }
  .search_right {
    width: 900px;
    .box-card {
      width: 100%;
      position: relative;
      .total_div {
        text-align: right;
        padding-bottom: 10px;
      }
    }
    .form_search {
      .el-form-item {
        margin-bottom: 0;
        padding: 10 26px;
      }
      .el-checkbox-group {
        display: inline;
        margin-left: 30px;
      }
    }
  }

}
</style>
